<template>
  <div>
    <div id="map"></div>
    <button @click="markerClick" style="width: 100px;height: 50px;">标记事件</button>

    <button @click="initDrawCtrl">初始化绘制控件</button><br>
    <button @click="destoryDrawCtr">销毁绘制控件</button><br>
    <button @click="markerClick">点</button>
    <button @click="startDraw(1)">圆</button>
    <button @click="startDraw(2)">线</button>
    <button @click="startDraw(3)">矩形</button>
    <button @click="startDraw(4)">多边形</button>
    <button @click="startDraw(5)">编辑</button>
    <button @click="startDraw(6)">删除</button>
    <button @click="stopDraw">清除</button>

  </div>
</template>
<script setup>
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import 'leaflet.chinatmsproviders';
import 'leaflet-polylinedecorator'

import { useData } from './getData'
import { useTools } from './drawTool'
import { featureLayer } from './featureLyer'
// import { editTools } from './editTool'
import { onMounted, ref, reactive } from 'vue'
const show = ref(false)
let map = reactive()
let drawControl = reactive()
let drawObj = reactive()
let drawLayerGrounp = reactive()

const initMap = () => {
  let arrLatlng = [];
  // 底图
  map = L.map('map', {
    center: [29.44916482692468, 106.47399902343751],//中心坐标
    zoom: null,//初始缩放，因为在下文写了展示全地图，所以这里设置空值，但必须写也可以设置
    minZoom: 3,
    maxZoom: 18,
    zoomControl: true, //缩放组件
    // attributionControl: false, //去掉右下角logol
    // layers://baseLayer对象的属性值组成的数组
    // pmIgnore: true//选型控制忽略图层
  })
  const getData = useData()
  let markerIcon = L.icon({
    // iconUrl: "https://unpkg.com/leaflet@1.9.3/dist/images/marker-icon.png",
    iconUrl: require("@/assets/leaflet/person1.png"),
    iconSize: [50, 50],
  });
  // 地区代码
  getData(map)
  // 地图点击事件
  map.on('click', function (e) {
    // 坐标，纬度前，经度后
    let latlng = e.latlng
    arrLatlng.push(latlng);
    // 放大
    // map.setView(e.latlng)
    getData(map)
    // 标记
    console.log("show", show.value);
    if (show.value == true) {
      L.marker(latlng, { icon: markerIcon }).addTo(map)
    }

    // ----------------------------------------------
    // 线段
    // if (arrLatlng.length > 1) {
    //   // 线段 连续线段--------------------------------------
    //   L.polyline(
    //     [arrLatlng[arrLatlng.length - 2], arrLatlng[arrLatlng.length - 1]],
    //     {
    //       opacity: 1,
    //       color: "green",
    //     }
    //   ).addTo(map);
    // }
    // // 多边形
    // if (arrLatlng.length == 6) { //指定多边形
    //   L.polygon(arrLatlng, { color: "red" }).addTo(map);
    // }
    // // 矩形
    // L.rectangle(
    //   arrLatlng.slice(arrLatlng.length - 2, arrLatlng.length),
    //   { color: "pink" }
    // ).addTo(map);
  })

  //声明图层组，存储城市标记marker-这些都属于overlays------featuregroup（layergroup）也属于overlays 和 layergroup（layer)---------------------------

  let osm = L.layerGroup()
  // 声明两个城市的坐标加入图层组
  let cq = L.marker([29.44916482692468, 106.47399902343751], { icon: markerIcon }).bindTooltip('这里是重庆');
  let qd = L.marker([35.51, 117.92], { icon: markerIcon }).bindTooltip('这里是青岛');
  let cities = L.layerGroup([cq, qd]);
  L.tileLayer("https://t0.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=d0cf74b31931aab68af181d23fa23d8d", { attribution: "天地图文字标注" }).addTo(cities);
  L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", { attribution: "OSM" }).addTo(osm);
  const featureOverlay = featureLayer(markerIcon)
  // 新建图层控件的数据源 - 城市
  const overlays = {
    '城市': cities,
    'osm': osm,
    ...featureOverlay
  };
  // 功能----------------------------------------
  // 地图底层数据
  const baseLayer = {
    '高德地图': L.tileLayer(
      "https://webrd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}",
      { subdomains: "1234" }
    ).addTo(map),
    'ArcGIS卫星影像': L.tileLayer(
      "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}.png", { attribution: "ArcGIS卫星影像" }
    ),
    '高德卫星地图': L.tileLayer(
      "https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
    ),
    '白色底图': L.tileLayer(
      "http://10.87.211.254:8099/title/{z}/{x}/{y}.png",
    ),
    'osm街道地图': L.tileLayer(
      // "https://tile-c.openstreetmap.fr/hot/{z}/{x}/{y}.png",
      "https://tile-b.openstreetmap.fr/hot/{z}/{x}/{y}.png",
    ),
    '天地图影像图': L.tileLayer(
      "http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d",
    ),
    '天地图街道图': L.tileLayer(
      "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d",
    ),
    '天地图地形晕染': L.tileLayer(
      "http://t4.tianditu.com/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d",
    ),
    '天地图矢量': L.tileLayer(
      "http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=d0cf74b31931aab68af181d23fa23d8d",
    ),
  }
  // 配置布局
  L.tileLayer("", { attribution: "卫星影像" }).addTo(map);
  // 地图底层控制
  L.control.layers(
    baseLayer, overlays, {
    position: 'topright'
  }
  ).addTo(map)

  // 添加绘制工具
  // editTools(map)
  useTools(map)


  // //1.绘制线
  let arrow = L.polyline(
    [
      [29.44916482692468, 106.47399902343751], [35.51, 117.92]
    ],
    {
      //颜色
      color: "red",
    }
  ).addTo(cities);
  //添加箭头
  L.polylineDecorator(arrow, {
    //添加模式
    patterns: [
      {
        //模式符号的偏移位置
        offset: "30%",
        //模式符号的重复间隔
        repeat: 20,
        //符号实例
        symbol: L.Symbol.arrowHead({
          //符号大小
          pixelSize: 15,
          //符号样式
          pathOptions: {
            //是否显示边线
            stroke: true,
          },
        }),
      },
    ],
  }).addTo(cities);
  // --------------------------------------要素叠



}

// 初始化绘制控件
const initDrawCtrl = () => {

  drawControl = new L.Control.Draw({
    draw: {
      polyline: true,
      polygon: true,
      rectangle: true,
      circle: true,
      marker: true,
      circlemarker: true,
    }
  })

}
// 交互绘制回调
// const drawCreatedBack = (e) => {
//   console.log('e', e);
//   console.log('绘制完成', e);
//   // 绘制的图形图层对象
//   let drawLayer = e.layer;
//   // 判断当前没有图层组，需先添加
//   // if (!drawLayerGrounp) {
//   //   //图层组
//   //   drawLayerGrounp = new L.FeatureGroup();
//   //   // 添加
//   //   map.addLayer(drawLayerGrounp);
//   // }
//   // 添加到图层组
//   drawLayerGrounp.addLayer(drawLayer);
// }
// 销毁绘制控件
const destoryDrawCtr = function () {
  // L.Control.Draw 控件对象
  drawControl = null;
  // 绘制对象
  drawObj = null;
  // 删除全部绘制的图层
  if (drawLayerGrounp) {
    drawLayerGrounp.clearLayers();
  }
  // 取消绘制完监听事件，避免在真正开发中，其它地方也监听了 CREATED 事件
  // map.off(L.Draw.Event.CREATED, drawCreatedBack());
}
// 启动绘制
const startDraw = function (idx) {
  // 先取消
  if (drawObj) {
    drawObj.disable();
  }
  switch (idx) {
    case 1: {// 圆
      drawObj = new L.Draw.Circle(map, drawControl.options.draw.circle);

      break;
    }
    case 2: {// 线
      drawObj = new L.Draw.Polyline(map, drawControl.options.draw.polyline);
      break;
    }
    case 3: {// 矩形
      drawObj = new L.Draw.Rectangle(map, drawControl.options.draw.rectangle);
      break;
    }
    case 4: {// 多边形
      drawObj = new L.Draw.Polygon(map, drawControl.options.draw.polygon);
      break;
    }
    case 5: {// 编辑

      drawObj = new L.EditToolbar.Edit(map, {
        featureGroup: new L.FeatureGroup(),
        selectedPathOptions: drawControl.options.edit.selectedPathOptions
      })

      break;
    }
    case 6: {// 删除
      drawObj = new L.EditToolbar.Delete(map, {
        featureGroup: new L.FeatureGroup()
      })
      break;
    }
  }
  // 启动 
  drawObj.enable();
  // 添加绘制完监听事件
  // map.on(L.Draw.Event.CREATED, drawCreatedBack());
}
//清除绘制
const stopDraw = function () {
  // 删除全部绘制的图层
  if (drawLayerGrounp) {
    drawLayerGrounp.clearLayers();
  }
  // 取消绘制操作
  drawObj.disable();
}
const markerClick = function () {
  show.value = !show.value
  console.log("show点击", show.value);
}

onMounted(() => {
  initMap()
  initDrawCtrl()
})
</script>

<style>
#map {
  height: 800px;
  width: 1000px;
  margin: auto;
  border: 10px solid pink;
  /* color: #88cfff; */
}
</style>